// 字符串工具类

/**
 * GBK解码
 * @param arr 整数数组，成员为一个16进制转换得到的10进制数
 */
export const decodeGBKArr = (arr: number[]) => {
    return new TextDecoder("GB18030").decode(new Uint8Array(arr))
}

/**
 * GBK解码
 * @param str 使用GBK编码的字符串，格式为百分号开头的16进制数，如  %D7%F3%C7%A3%BB%C6%D3%D2%C7%DC%B2%D4   --> 左牵黄右擒苍
 */
export const decodeGBK = (str?: string) => {
    if (!str) {
        return undefined
    }
    let arr = []
    while (str) {
        if (str.startsWith("%")) {
            arr.push(parseInt(str.substring(1, 3), 16))
            str = str.substring(3)
        } else {
            arr.push(str.charCodeAt(0))
            str = str.substring(1)
        }
    }
    return decodeGBKArr(arr)
}
/**
 * 反转义
 * @param text 待处理字符串
 */
export const unEscape = (text?: string) => {
    if (!text) {
        return undefined
    }
    const div = document.createElement("div");
    div.innerHTML = !text ? "" : text.replace(/<br\/>/g, '\n');
    let res = div.innerText || div.textContent;
    return res ? res : undefined;
}
/**
 * 解码字符串中的unicode字符
 * @param text 字符串
 */
export const decodeUnicode = (text?: string) => {
    return !text ? undefined : text.replace(/&#(\d+);/g, (_, $1) => String.fromCodePoint($1));
}

export const decode = (text?: string) => decodeUnicode(unEscape(text))

/**
 * 解析bit数据
 * @param bit bit
 */
export const parseBit = (bit: string | number) => {
    bit = Number(bit)
    return bit.toString(2).split("").reverse().join('')
}